<template>
  <div style="width: 100%; height: 100%">
    <el-header class="el-header">
      <div class="header-back-container">
        <div class="el-page-header">
          <div class="el-page-header__left" @click="onBack">
            <i class="el-icon-back"></i>
            <div class="el-page-header__title">返回</div>
          </div>
          <div class="el-page-header__content">
            <div class="title-box">
              <div class="title">
                {{ editData && editData.id ? "编辑规则" : "新增规则" }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-header>
    <el-main style="height: calc(100% - 60px - 60px); overflow-y: auto">
      <div class="form">
        <el-form
          :model="addForm"
          :rules="rules"
          ref="refAddForm"
          label-width="110px"
          style="margin: 0px 8px"
        >
          <!-- <div class="step-box">
            <div class="step-title">
              <div class="step-icon"></div>
              <div class="step-num">1/4</div>
            </div>
            <div class="step-container">
              <div class="title">联动规则类型</div>
              <div class="content rule-type">
                <el-radio-group v-model="type">
                  <el-radio :label="1" border
                    >A设备上报属性，联动A设备报警</el-radio
                  >
                  <el-radio :label="2" border
                    >A设备上报数据，联动B设备下发指令</el-radio
                  >
                </el-radio-group>
              </div>
            </div>
          </div> -->
          <div class="step-box">
            <div class="step-title">
              <div class="step-icon"></div>
              <div class="step-num">1/3</div>
            </div>
            <div class="step-container">
              <div class="title">联动规则</div>
              <div class="content rule-type">
                <el-form-item size="small" label="规则名称" prop="name">
                  <el-input
                    clearable
                    v-model.trim="addForm.name"
                    placeholder="请输入"
                    maxlength="20"
                    style="width: 100%"
                  >
                  </el-input>
                </el-form-item>
                <el-form-item size="small" label="场景描述" prop="description">
                  <el-input
                    placeholder="请输入场景描述"
                    maxlength="50"
                    rows="3"
                    type="textarea"
                    v-model="addForm.description"
                    resize="none"
                    :autosize="{ minRows: 2, maxRows: 5 }"
                  ></el-input>
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="step-box">
            <div class="step-title">
              <div class="step-icon"></div>
              <div class="step-num">2/3</div>
            </div>
            <div class="step-container">
              <div class="title">选择触发源</div>
              <div class="content rule-type">
                <el-form-item
                  size="small"
                  label="设备型号"
                  prop="listeners[0].pkIds"
                  :rules="[
                    {
                      type: 'array',
                      required: true,
                      message: '请选择',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-cascader
                    v-model="addForm.listeners[0].pkIds"
                    :props="cascaderProps"
                    style="width: 100%"
                    ref="refElcascader"
                    @change="onChangeCascader($event, true)"
                  ></el-cascader>
                </el-form-item>
                <el-form-item size="small" label="触发范围">
                  <el-radio-group
                    v-model="addForm.listeners[0].radius.type"
                    fill="#ffffff"
                    @input="changeRadio($event, 'trigger')"
                    :disabled="
                      !addForm.listeners[0].pkIds ||
                      !addForm.listeners[0].pkIds.length
                    "
                  >
                    <el-radio label="all">全部</el-radio>
                    <el-radio label="org">联网单位</el-radio>
                    <el-radio label="space">场所</el-radio>
                    <el-radio label="device">设备</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- 范围选择组件(触发源) -->
                <Range
                  ref="refRangeTrigger"
                  v-if="
                    addForm.listeners[0].radius.type &&
                    addForm.listeners[0].radius.type != 'all'
                  "
                  :resource="addForm.listeners[0].radius.type"
                  :rangeData="rangeData"
                  :watchIndex="watchIndex"
                  :productId="addForm.listeners[0].productId"
                  :classMark="addForm.listeners[0].classMark"
                  @onPushData="onPushData"
                ></Range>
                <div
                  v-for="(item, index) in addForm.listeners[0].conditions"
                  :key="item.key"
                  class="conditions"
                >
                  <el-form-item
                    size="small"
                    :label="'触发条件' + (index + 1)"
                    class="is-required"
                  >
                  </el-form-item>
                  <div
                    style="
                      width: calc(100% - 100px);
                      display: flex;
                      align-items: center;
                    "
                  >
                    <div
                      style="
                        width: calc(100% - 18px);
                        display: flex;
                        align-items: center;
                      "
                    >
                      <!-- 选择类型 -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].identifier`"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                      >
                        <el-select
                          v-model="item.identifier"
                          placeholder="请选择"
                          size="small"
                          style="width: 98%"
                          @change="(e) => conditionChange(item, index, e)"
                        >
                          <el-option-group
                            v-for="(group, d) in options"
                            :key="d"
                            :label="group.name"
                          >
                            <el-option
                              v-for="(item2, i) in group.items"
                              :key="i"
                              :label="item2.name"
                              :value="item2.identifier"
                            >
                            </el-option>
                          </el-option-group>
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        v-if="item.identifier == 'report'"
                        :prop="`listeners[0].conditions[${index}].parameters[0].identifier`"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                      >
                        <el-select
                          v-model="item.parameters[0].identifier"
                          style="width: 98%"
                          placeholder="请选择"
                          size="small"
                          @change="onChangeProperties($event, index)"
                        >
                          <el-option
                            v-for="p in properties"
                            :label="p.name"
                            :value="p.identifier"
                            :key="p.identifier"
                          />
                        </el-select>
                      </el-form-item>
                      <!-- 事件 -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].identifier`"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                        v-else-if="
                          !item?.identifier?.endsWith(':*') &&
                          item.identifier &&
                          item.identifier != 'report'
                        "
                      >
                        <el-select
                          v-model="item.parameters[0].identifier"
                          style="width: 98%"
                          placeholder="请选择"
                          size="small"
                          @change="onChangeEvents($event, index)"
                        >
                          <el-option
                            v-for="(p, i) in outputData"
                            :label="p.name"
                            :value="p.identifier"
                            :key="i"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].comparator`"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                        v-if="
                          !item?.identifier?.endsWith(':*') &&
                          (item.specsType == 'int32' ||
                            item.specsType == 'float' ||
                            item.specsType == 'text')
                        "
                      >
                        <el-select
                          v-model="item.parameters[0].comparator"
                          style="width: 98%"
                          @change="forceUpdate"
                          size="small"
                        >
                          <el-option
                            v-for="cp in comparators"
                            :label="cp.name"
                            :value="cp.value"
                            :key="cp.value"
                          />
                        </el-select>
                      </el-form-item>
                      <!-- 属性 -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                        v-if="
                          item.identifier == 'report' &&
                          (item.specsType == 'enum' || item.specsType == 'bool')
                        "
                      >
                        <el-select
                          v-model="item.parameters[0].value"
                          style="width: 98%"
                          placeholder="请选择"
                          @change="forceUpdate(true)"
                          size="small"
                        >
                          <el-option
                            v-for="v in item.specsArray"
                            :label="v.value"
                            :value="v.key"
                            :key="v.key"
                          />
                        </el-select>
                      </el-form-item>
                      <!-- 属性 int32 -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-if="
                          item.identifier == 'report' &&
                          item.specsType == 'int32'
                        "
                      >
                        <el-input
                          v-model="item.parameters[0].value"
                          auto-complete="off"
                          @input="forceUpdate(true)"
                          style="width: 98%"
                          size="small"
                          :placeholder="
                            item.dataType.specs.min +
                            '-' +
                            item.dataType.specs.max
                          "
                          :oninput="`if(isNaN(value)) { value = null } {if(value>${item.dataType.specs.max})value=${item.dataType.specs.max}} {if(value<${item.dataType.specs.min})value=${item.dataType.specs.min}}`"
                        />
                      </el-form-item>
                      <!-- 属性 float -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-else-if="
                          item.identifier == 'report' &&
                          item.specsType == 'float'
                        "
                      >
                        <el-input
                          v-model="item.parameters[0].value"
                          auto-complete="off"
                          size="small"
                          style="width: 98%"
                          @input="forceUpdate(true)"
                          :placeholder="
                            item.dataType.specs.min +
                            '-' +
                            item.dataType.specs.max
                          "
                          :oninput="`if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} {if(value>${item.dataType.specs.max})value=${item.dataType.specs.max}} {if(value<${item.dataType.specs.min})value=${item.dataType.specs.min}}`"
                        />
                      </el-form-item>
                      <!-- 属性 text -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-else-if="
                          item.identifier == 'report' &&
                          item.specsType == 'text'
                        "
                      >
                        <el-input
                          v-model="item.parameters[0].value"
                          auto-complete="off"
                          size="small"
                          style="width: 98%"
                          @input="forceUpdate(true)"
                          placeholder="请输入"
                          :maxlength="item.dataType.specs.length"
                        />
                      </el-form-item>
                      <!-- 属性 date -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="flex: 1"
                        :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-else-if="
                          item.identifier == 'report' &&
                          item.specsType == 'date'
                        "
                      >
                        <el-input
                          v-model="item.parameters[0].value"
                          auto-complete="off"
                          size="small"
                          placeholder="毫秒"
                          @input="forceUpdate(true)"
                        />
                      </el-form-item>

                      <!-- 事件 -->
                      <div v-for="(item2, index) in eventsList" :key="index">
                        <!-- style="margin-left: 8px" -->
                        <div v-for="(item3, i) in item2.outputData" :key="i">
                          <!-- <div
                            v-if="
                              item.identifier == item2.identifier &&
                              item.parameters[0].identifier ==
                                item3.identifier &&
                              item3.dataType.type == 'json'
                            "
                          >
                            <el-form-item
                              size="small"
                              label-width="0"
                              style="flex: 1"
                              :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                              :rules="[
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change',
                                },
                              ]"
                              v-if="
                                item3.dataType.type == 'json'
                              "
                            >
                              <el-select
                                v-model="item.parameters[0].value"
                                size="small"
                                style="width: 98%"
                                @change="forceUpdate"
                              >
                                <el-option
                                  v-for="cp in item3.dataType.specsArray"
                                  :label="cp.value"
                                  :value="cp.key"
                                  :key="cp.key"
                                />
                              </el-select>
                            </el-form-item>
                          </div> -->
                          <div
                            v-if="
                              item.identifier == item2.identifier &&
                              item.parameters[0].identifier == item3.identifier
                            "
                          >
                            <el-form-item
                              size="small"
                              label-width="0"
                              style="flex: 1"
                              :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                              :rules="[
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'change',
                                },
                              ]"
                              v-if="
                                item3.dataType.type == 'enum' ||
                                item3.dataType.type == 'bool'
                              "
                            >
                              <el-select
                                v-model="item.parameters[0].value"
                                size="small"
                                style="width: 98%"
                                @change="forceUpdate"
                              >
                                <el-option
                                  v-for="cp in item3.dataType.specsArray"
                                  :label="cp.value"
                                  :value="cp.key"
                                  :key="cp.key"
                                />
                              </el-select>
                            </el-form-item>
                            <el-form-item
                              size="small"
                              label-width="0"
                              style="flex: 1"
                              :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                              :rules="[
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'blur',
                                },
                              ]"
                              v-else-if="item3.dataType.type == 'int32'"
                            >
                              <el-input
                                v-model="item.parameters[0].value"
                                auto-complete="off"
                                size="small"
                                style="width: 98%"
                                :placeholder="
                                  item3.dataType.specs.min +
                                  '-' +
                                  item3.dataType.specs.max
                                "
                                :oninput="`if(isNaN(value)) { value = null } {if(value>${item3.dataType.specs.max})value=${item3.dataType.specs.max}} {if(value<${item3.dataType.specs.min})value=${item3.dataType.specs.min}}`"
                              />
                            </el-form-item>
                            <el-form-item
                              size="small"
                              label-width="0"
                              style="flex: 1"
                              :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                              :rules="[
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'blur',
                                },
                              ]"
                              v-else-if="item3.dataType.type == 'float'"
                            >
                              <el-input
                                v-model="item.parameters[0].value"
                                auto-complete="off"
                                size="small"
                                style="width: 98%"
                                @input="forceUpdate"
                                :placeholder="
                                  item3.dataType.specs.min +
                                  '-' +
                                  item3.dataType.specs.max
                                "
                                :oninput="`if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} {if(value>${item3.dataType.specs.max})value=${item3.dataType.specs.max}} {if(value<${item3.dataType.specs.min})value=${item3.dataType.specs.min}}`"
                              />
                            </el-form-item>
                            <el-form-item
                              size="small"
                              label-width="0"
                              style="flex: 1"
                              :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                              :rules="[
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'blur',
                                },
                              ]"
                              v-else-if="item3.dataType.type == 'text'"
                            >
                              <el-input
                                v-model="item.parameters[0].value"
                                auto-complete="off"
                                size="small"
                                style="width: 98%"
                                @input="forceUpdate"
                                :maxlength="item3.dataType.specs.length"
                              />
                            </el-form-item>
                            <el-form-item
                              size="small"
                              label-width="0"
                              style="flex: 1"
                              :prop="`listeners[0].conditions[${index}].parameters[0].value`"
                              :rules="[
                                {
                                  required: true,
                                  message: '请选择',
                                  trigger: 'blur',
                                },
                              ]"
                              v-else-if="item3.dataType.type == 'date'"
                            >
                              <el-input
                                v-model="item.parameters[0].value"
                                auto-complete="off"
                                size="small"
                                placeholder="毫秒"
                                @input="forceUpdate"
                              />
                            </el-form-item>
                          </div>
                        </div>
                      </div>
                    </div>
                    <i
                      class="el-icon-delete"
                      @click="onRemoveCondition(index)"
                      v-if="addForm.listeners[0].conditions.length > 1"
                    ></i>
                  </div>
                </div>
                <el-form-item size="small" label="">
                  <div class="addCondition" @click="onAddCondition">
                    <div class="addCondition-box">
                      <i class="el-icon-plus"></i>
                      <span
                        >添加 ({{
                          this.addForm.listeners[0].conditions.length
                        }}/3)</span
                      >
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </div>
          <div class="step-box">
            <div class="step-title">
              <div class="step-icon"></div>
              <div class="step-num">3/3</div>
            </div>
            <div class="step-container">
              <div class="title">选择执行源</div>
              <div class="content rule-type">
                <div class="deviceModel">
                  <el-form-item
                    size="small"
                    label="设备型号"
                    class="is-required"
                  >
                  </el-form-item>
                  <div
                    style="
                      width: calc(100% - 110px);
                      display: flex;
                      flex-wrap: wrap;
                      align-items: center;
                    "
                  >
                    <div
                      v-for="(item, index) in addForm.actions"
                      :key="item.config.id"
                      class="execute-model"
                      :class="[item.config.checked ? 'active' : '']"
                      @click.prevent="onSelectDeviceModel(index)"
                    >
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="width: 90%; margin-right: 2%"
                        :prop="`actions[${index}].config.pkIds`"
                        :rules="[
                          {
                            type: 'array',
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                      >
                        <el-cascader
                          v-model="item.config.pkIds"
                          :props="cascaderProps2"
                          style="width: 100%"
                          ref="refElcascader2"
                          @change="onChangeCascader2($event, true, index)"
                        ></el-cascader>
                      </el-form-item>
                      <i
                        class="el-icon-delete"
                        @click.stop="onRemoveDeviceModel(index)"
                        v-if="addForm.actions.length > 1"
                      ></i>
                    </div>
                  </div>
                </div>
                <el-form-item size="small" label="">
                  <div class="addCondition" @click="onAddDeviceModel">
                    <div class="addCondition-box">
                      <i class="el-icon-plus"></i>
                      <span>添加 ({{ addForm.actions.length }}/5)</span>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item size="small" label="执行范围">
                  <el-radio-group
                    v-model="
                      addForm.actions[currentExecuteIndex].config.radius.type
                    "
                    @input="changeRadio($event, 'execute')"
                    :disabled="
                      !addForm.actions[currentExecuteIndex].config.pkIds ||
                      !addForm.actions[currentExecuteIndex].config.pkIds.length
                    "
                  >
                    <el-radio label="all">全部</el-radio>
                    <el-radio label="org">联网单位</el-radio>
                    <el-radio label="space">场所</el-radio>
                    <el-radio label="device">设备</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- 范围选择组件(执行源) -->
                <Range2
                  ref="refRangeExecute"
                  v-if="addForm.actions[currentExecuteIndex].config.radius.type"
                  :resource="
                    addForm.actions[currentExecuteIndex].config.radius.type
                  "
                  :rangeData="rangeData2"
                  :watchIndex="watchIndex2"
                  :productId="
                    addForm.actions[currentExecuteIndex].config.productId
                  "
                  :classMark="
                    addForm.actions[currentExecuteIndex].config.classMark
                  "
                  @onPushData="onPushData"
                ></Range2>
                <div class="deviceModel">
                  <el-form-item
                    size="small"
                    label="设置联动动作"
                    class="is-required"
                  >
                  </el-form-item>
                  <div style="flex: 1; display: flex; align-items: center">
                    <!-- 服务选择 -->
                    <el-form-item
                      size="small"
                      label-width="0"
                      :prop="`actions[${currentExecuteIndex}].config.services[0].identifier`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择',
                          trigger: 'change',
                        },
                      ]"
                    >
                      <el-select
                        v-model="
                          addForm.actions[currentExecuteIndex].config
                            .services[0].identifier
                        "
                        @change="serviceSelected"
                        filterable
                        placeholder="请选择"
                        style="width: 95%"
                      >
                        <el-option
                          v-for="s in servicesList || []"
                          :label="s.name"
                          :value="s.identifier"
                          :key="s.identifier"
                        />
                      </el-select>
                    </el-form-item>
                    <!-- 输入选择 -->
                    <el-form-item
                      size="small"
                      label-width="0"
                      :prop="`actions[${currentExecuteIndex}].config.services[0].equalValue`"
                      :rules="[
                        {
                          required: true,
                          message: '请选择',
                          trigger: 'change',
                        },
                      ]"
                      v-if="
                        addForm.actions[currentExecuteIndex].config.services[0]
                          .identifier
                      "
                    >
                      <el-select
                        v-model="
                          addForm.actions[currentExecuteIndex].config
                            .services[0].equalValue
                        "
                        @change="
                          serviceSelectedItem(
                            $event,
                            addForm.actions[currentExecuteIndex].config
                              .services[0].inputData
                          )
                        "
                        filterable
                        size="small"
                        placeholder="请选择"
                        style="width: 95%"
                      >
                        <el-option
                          v-for="s in addForm.actions[currentExecuteIndex]
                            .config.services[0].inputData || []"
                          :label="s.name"
                          :value="s.identifier"
                          :key="s.identifier"
                        />
                      </el-select>
                    </el-form-item>
                    <!-- 具体动作 -->
                    <!-- v-for="(v, i) in addForm.actions[currentExecuteIndex]
                      .config.services[0].inputData"
                    :key="i" -->
                    <div
                      style="display: flex"
                      v-if="
                        addForm.actions[currentExecuteIndex].config.services[0]
                          .equalValue
                      "
                    >
                      <el-form-item
                        size="small"
                        label-width="0"
                        v-if="
                          currentDataItem.dataType.type == 'enum' ||
                          currentDataItem.dataType.type == 'bool'
                        "
                        :prop="`actions[${currentExecuteIndex}].config.services[0].inputData[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请选择',
                            trigger: 'change',
                          },
                        ]"
                      >
                        <el-select
                          v-model="
                            addForm.actions[currentExecuteIndex].config
                              .services[0].inputData[0].value
                          "
                          @change="forceUpdate(true)"
                          filterable
                          size="small"
                          placeholder="请选择"
                          style="width: 95%"
                        >
                          <el-option
                            v-for="s in currentDataItem.dataType.typeList || []"
                            :label="s.label"
                            :value="s.value"
                            :key="s.value"
                          />
                        </el-select>
                      </el-form-item>

                      <!-- 服务 int32 -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="width: 95%"
                        :prop="`actions[${currentExecuteIndex}].config.services[0].inputData[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-if="currentDataItem.dataType.type == 'int32'"
                      >
                        <el-input
                          v-model="
                            addForm.actions[currentExecuteIndex].config
                              .services[0].inputData[0].value
                          "
                          auto-complete="off"
                          @input="forceUpdate"
                          style="width: 98%"
                          size="small"
                          :placeholder="
                            currentDataItem.dataType.specs.min +
                            '-' +
                            currentDataItem.dataType.specs.max
                          "
                          :oninput="`if(isNaN(value)) { value = null } {if(value>${currentDataItem.dataType.specs.max})value=${currentDataItem.dataType.specs.max}} {if(value<${currentDataItem.dataType.specs.min})value=${currentDataItem.dataType.specs.min}}`"
                        />
                      </el-form-item>
                      <!-- 服务 float -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="width: 95%"
                        :prop="`actions[${currentExecuteIndex}].config.services[0].inputData[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-else-if="currentDataItem.dataType.type == 'float'"
                      >
                        <el-input
                          v-model="
                            addForm.actions[currentExecuteIndex].config
                              .services[0].inputData[0].value
                          "
                          auto-complete="off"
                          size="small"
                          style="width: 98%"
                          @input="forceUpdate"
                          :placeholder="
                            currentDataItem.dataType.specs.min +
                            '-' +
                            currentDataItem.dataType.specs.max
                          "
                          :oninput="`if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)} {if(value>${currentDataItem.dataType.specs.max})value=${currentDataItem.dataType.specs.max}} {if(value<${currentDataItem.dataType.specs.min})value=${currentDataItem.dataType.specs.min}}`"
                        />
                      </el-form-item>
                      <!-- 服务 text -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="width: 95%"
                        :prop="`actions[${currentExecuteIndex}].config.services[0].inputData[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-else-if="currentDataItem.dataType.type == 'text'"
                      >
                        <el-input
                          v-model="
                            addForm.actions[currentExecuteIndex].config
                              .services[0].inputData[0].value
                          "
                          auto-complete="off"
                          size="small"
                          style="width: 98%"
                          @input="forceUpdate"
                          placeholder="请输入"
                          :maxlength="currentDataItem.dataType.specs.length"
                        />
                      </el-form-item>
                      <!-- 服务 date -->
                      <el-form-item
                        size="small"
                        label-width="0"
                        style="width: 95%"
                        :prop="`actions[${currentExecuteIndex}].config.services[0].inputData[0].value`"
                        :rules="[
                          {
                            required: true,
                            message: '请输入',
                            trigger: 'blur',
                          },
                        ]"
                        v-else-if="currentDataItem.dataType.type == 'date'"
                      >
                        <el-input
                          v-model="
                            addForm.actions[currentExecuteIndex].config
                              .services[0].inputData[0].value
                          "
                          auto-complete="off"
                          size="small"
                          placeholder="毫秒"
                          @input="forceUpdate"
                        />
                      </el-form-item>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>
    </el-main>
    <el-footer class="dialog-footer">
      <el-button size="small" @click="closeAddDialog">取 消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="addSubmit"
        v-preventReClick="1000"
        >确 定</el-button
      >
    </el-footer>
  </div>
</template>

<script>
import tableStyleMixin from "@mixin/table-style";
import { mapState, mapMutations } from "vuex";
import { reqProductList, reqProductModelPage } from "@/api/api";
import { reqRuleEdit } from "@api/rule";
import { reqByProductKey } from "@/api/rule";
import Range from "./range.vue";
import Range2 from "./range2.vue";
import rules from "../../isolateManage/mixins/rules";
// import { codemirror } from "vue-codemirror";
export default {
  name: "",
  props: ["editData"],
  components: {
    Range,
    Range2,
    // codemirror,
  },
  watch: {
    editData: {
      handler(val) {
        if (JSON.stringify(val) == "{}") return;
        this.isEditInfo = true;
        let data = JSON.parse(JSON.stringify(val));
        this.addForm.name = data.name;
        this.addForm.type = data.type;
        this.addForm.description = data.description;
        this.addForm.tenantId = data.tenantId;

        // 触发
        // this.addForm.listeners[0] = JSON.parse(
        //   JSON.parse(data.listeners)[0].config
        // );
        let listeners_copy = JSON.parse(JSON.parse(data.listeners)[0].config);
        this.addForm.listeners[0].classMark = listeners_copy.classMark;
        this.addForm.listeners[0].pk = listeners_copy.pk;
        this.addForm.listeners[0].productId = listeners_copy.productId;
        this.addForm.listeners[0].radius = listeners_copy.radius;
        this.addForm.listeners[0].type = listeners_copy.type;
        this.addForm.listeners[0].conditions = listeners_copy.conditions;
        this.addForm.listeners[0].pkIds = listeners_copy.pkIds.split(",");

        this.currentDeviceType = this.addForm.listeners[0].pk;
        this.onChangeCascader([], false, true);
        this.changeRadio(this.addForm.listeners[0].radius.type, "trigger");

        // 执行
        this.addForm.actions = JSON.parse(data.actions);
        this.addForm.actions.forEach((item, index) => {
          item.config = JSON.parse(item.config);
          item.config.pkIds = item.config.pkIds.split(",");
          if (index == 0) {
            item.config.checked = true;
            this.currentDeviceType2 = item.config.pk;
          }
        });
        // 赋值currentDataItem(服务-输入)
        this.addForm.actions[0].config.services[0].inputData.forEach(
          (item2, index2) => {
            if (
              item2.identifier ==
              this.addForm.actions[0].config.services[0].equalValue
            ) {
              this.currentDataItem = item2;
            }
          }
        );
        this.onChangeCascader2([], false, 0, true);
        this.changeRadio(this.addForm.actions[0].config.radius.type, "execute");
        this.currentIndex = 0;
      },
      deep: true,
      immediate: true,
    },
  },
  mixins: [tableStyleMixin],
  data() {
    return {
      isEditInfo: false,
      addForm: {
        name: "",
        type: "scene",
        description: "",
        tenantId: "",
        filters: [],
        listeners: [
          {
            pkIds: [],
            type: "device", // 类型：设备
            pk: "", // 设备主键：门磁
            conditions: [
              // 条件：满足以下条件时触发
              {
                dataType: {},
                identifier: "", // 报告标识符：触发报告
                parameters: [
                  // 参数：检查具体参数的值
                  {
                    identifier: "", // 标识符：门磁的ecl参数
                    comparator: "", // 比较符：小于
                    value: "", // 比较值：1
                  },
                ],
                specsArray: [], // 规格数组
                specsType: "",
                type: "", // 类型：属性类型
                key: Date.now(),
              },
            ],
            radius: {
              type: "all", //类型： all 全部 、org 组织、 space 单位、 device 设备
              assemble: [],
              deviceAssemble: [],
              spaceAssemble: [],
              orgAssemble: [],
            },
            classMark: "",
            productId: "",
          },
        ],
        actions: [
          {
            config: {
              id: Date.now(),
              services: [
                {
                  // 设备控制
                  identifier: "",
                  inputData: [
                    {
                      identifier: "",
                      dataType: {
                        type: "",
                        specs: {},
                      },
                      name: "",
                      required: false,
                      value: "",
                    },
                  ],
                  saved: true,
                  value: "",
                  equalValue: "",
                },
              ],
              pk: "", // 设备主键：门磁
              radius: {
                type: "all", //类型： all 全部 、org 组织、 space 单位、 device 设备
                assemble: [], //集合id
                deviceDn: [],
                spaceDn: [],
                orgDn: [],
              },
              identifier: "",
              pkIds: "",
              checked: true,
              classMark: "",
            },
            type: "", // 类型：设备控制: device  通知: alert
          },
        ],
        triggerDeviceType: [],
        executingDeviceType: [],
        username: "",
      },
      rules: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      cascaderProps: {
        lazy: true,
        lazyLoad: async (node, resolve) => {
          if (node.level == 0) {
            let res = await reqProductList();
            if (res.code !== 20000)
              return this.$modal.notifyWarning(res.message);
            if (res.data.rows.length) {
              const nodes = res.data.rows.map((item) => ({
                value: item.id,
                label: item.name,
                type: item.deviceType,
              }));
              this.productList = res.data.rows;
              resolve(nodes);
            }
          } else if (node.level == 1) {
            let res = await reqProductModelPage(1, 99, {
              productId: node.data.value,
              model: "",
            });
            if (res.code !== 20000)
              return this.$modal.notifyWarning(res.message);
            if (res.data.rows.length) {
              const nodes = res.data.rows.map((item) => ({
                value: item.id,
                label: item.model,
                leaf: node.level >= 1,
              }));
              // this.classMarkList = res.data.rows;
              // if ((node && node.data && node.data.type) || "") {
              //   this.currentDeviceType = node.data.type;
              //   this.triggerDeviceType = node.data.type;
              //   this.addForm.listeners[0].productId = node.data.value;
              // }
              resolve(nodes);
            }
          }
        },
      },
      currentDeviceType: "",
      cascaderProps2: {
        lazy: true,
        lazyLoad: async (node, resolve) => {
          if (node.level == 0) {
            let res = await reqProductList();
            if (res.code !== 20000)
              return this.$modal.notifyWarning(res.message);
            if (res.data.rows.length) {
              const nodes = res.data.rows.map((item) => ({
                value: item.id,
                label: item.name,
                type: item.deviceType,
              }));
              resolve(nodes);
            }
          } else if (node.level == 1) {
            let res = await reqProductModelPage(1, 99, {
              productId: node.data.value,
              model: "",
            });
            if (res.code !== 20000)
              return this.$modal.notifyWarning(res.message);
            if (res.data.rows.length) {
              const nodes = res.data.rows.map((item) => ({
                value: item.id,
                label: item.model,
                leaf: node.level >= 1,
              }));
              if ((node && node.data && node.data.type) || "") {
                // this.executingDeviceType = node.data.type;
                // this.currentDeviceType2 = node.data.type;
                // this.addForm.actions[
                //   this.currentExecuteIndex
                // ].config.productId = node.data.value;
              }
              resolve(nodes);
            }
          }
        },
      },
      productList: [],

      propertiesList: [],
      servicesList: [],
      currentDeviceType2: "",

      // 产品、型号
      eventsList: [],
      options: [],
      properties: [],
      outputData: [],
      comparators: [
        { name: "大于", value: ">" },
        { name: "等于", value: "==" },
        { name: "小于", value: "<" },
        { name: "不等于", value: "!=" },
        { name: "包含", value: "in" },
        { name: "不包含", value: "notin" },
        { name: "相似", value: "like" },
        { name: "任意", value: "*" },
      ],
      listenerIndex: 0, // 用于记录触发选择条件的索引，将属性存储，判断是否显示comparators

      rangeType: "", // trigger: 触发源；execute: 执行源
      rangeData: [],
      watchIndex: 0,
      rangeData2: [],
      watchIndex2: 0,
      currentExecuteIndex: 0,

      cmOptions: {
        mode: "text/javascript",
        gutters: [
          "CodeMirror-lint-markers",
          "CodeMirror-linenumbers",
          "CodeMirror-foldgutter",
        ],
        lineNumbers: true,
        line: true,
        lint: true,
        lineWrapping: true,
        autofocus: true,
        autoCloseBrackets: true,
        foldGutter: true, // 块槽
        hintOptions: { completeSingle: true },
        matchTags: { bothTags: true },
        matchBrackets: true,
        showCursorWhenSelecting: true,
        styleSelectedText: true,
        styleActiveLine: true,
        autoRefresh: true,
        highlightSelectionMatches: {
          minChars: 2,
          trim: true,
          style: "matchhighlight",
          showToken: false,
        },
      },
      codemirrorStyle: {
        fontSize: "18px",
        lineHeight: "150%",
        height: "450px",
        border: "1px solid #EBEEF5",
      },

      // 执行输入事件
      currentDataItem: {},

      timer: null,
      timer2: null,
    };
  },
  computed: {
    ...mapState(["user", "spacesManage"]),
  },
  methods: {
    // ———————— 触发源 ————————
    // 范围选择
    changeRadio(e, type) {
      console.log(type, "type");
      this.rangeType = type;
      if (type == "trigger") {
        if (e == "org") {
          this.$nextTick(() => {
            this.watchIndex++;
            this.rangeData = this.addForm.listeners[0].radius.orgAssemble;
            this.$refs.refRangeTrigger.getInfo()
              this.$refs.refRangeTrigger.getOrgList()
          });
        } else if (e == "device") {
          this.$nextTick(async () => {
            this.watchIndex++;
            this.rangeData = this.addForm.listeners[0].radius.deviceAssemble;
            this.timer && clearTimeout(this.timer);
            this.timer = setTimeout(() => {
              this.$refs.refRangeTrigger.searchForm.searchInput = "";
              this.$refs.refRangeTrigger.pageDev = 1;
              this.$refs.refRangeTrigger.getDataList();
            }, 200);
          });
        } else if (e == "space") {
          this.$nextTick(() => {
            this.watchIndex++;
            this.rangeData = this.addForm.listeners[0].radius.spaceAssemble;
            this.timer && clearTimeout(this.timer);
            this.timer = setTimeout(() => {
              this.$refs.refRangeTrigger.searchForm.searchInput = "";
              this.$refs.refRangeTrigger.page = 1;
              this.$refs.refRangeTrigger.getreqParkList();
            }, 200);
          });
        }
      } else if (type == "execute") {
        if (e == "org") {
          this.$nextTick(() => {
            this.watchIndex2++;
            this.rangeData2 =
              this.addForm.actions[
                this.currentExecuteIndex
              ].config.radius.orgDn;
              this.$refs.refRangeExecute.getInfo()
              this.$refs.refRangeExecute.getOrgList()
          });
        } else if (e == "device") {
          this.$nextTick(() => {
            this.watchIndex2++;
            this.rangeData2 =
              this.addForm.actions[
                this.currentExecuteIndex
              ].config.radius.deviceDn;
            this.timer2 && clearTimeout(this.timer2);
            this.timer2 = setTimeout(() => {
              this.$refs.refRangeExecute.searchForm.searchInput = "";
              this.$refs.refRangeExecute.pageDev = 1;
              this.$refs.refRangeExecute.getDataList();
            }, 200);
          });
        } else if (e == "space") {
          this.$nextTick(() => {
            this.watchIndex2++;
            this.rangeData2 =
              this.addForm.actions[
                this.currentExecuteIndex
              ].config.radius.spaceDn;
            this.timer2 && clearTimeout(this.timer2);
            this.timer2 = setTimeout(() => {
              this.$refs.refRangeExecute.searchForm.searchInput = "";
              this.$refs.refRangeExecute.page = 1;
              this.$refs.refRangeExecute.getreqParkList();
            }, 200);
          });
        }
      }

      this.forceUpdate();
    },
    onChangeCascader(e = [], clear = false, init) {
      if (clear) {
        this.onClearTriggerConditions();
        let mark = this.$refs.refElcascader.getCheckedNodes()[0].data.label;
        this.addForm.listeners[0].classMark = mark;
        if (this.addForm.listeners[0].radius.type == "device") {
          this.changeRadio("device", "trigger");
        }
      } else {
        if (!init) {
          let mark = this.$refs.refElcascader.getCheckedNodes()[0].data.label;
          this.addForm.listeners[0].classMark = mark;
          // this.addForm.triggerDeviceType = [mark];
          if (this.addForm.listeners[0].radius.type == "device") {
            this.changeRadio("device", "trigger");
          }
        }
      }
      // 赋值
      if (this.productList.length) {
        let type = this.productList.filter((item) => item.id == e[0])[0]
          .deviceType;
        this.currentDeviceType = type;
        this.triggerDeviceType = type;
        this.addForm.listeners[0].productId = e[0];
      }
      //初始化物模型
      this.addForm.listeners[0].pk = this.currentDeviceType;
      this.onThingModel(this.currentDeviceType);
    },
    // 清空触发条件
    onClearTriggerConditions() {
      // 清空前的逻辑
      this.addForm.listeners[0].conditions = [
        {
          dataType: {},
          identifier: "", // 报告标识符：触发报告
          parameters: [
            // 参数：检查具体参数的值
            {
              identifier: "", // 标识符：门磁的ecl参数
              comparator: "", // 比较符：小于
              value: "", // 比较值：1
            },
          ],
          specsArray: [], // 规格数组
          specsType: "",
          type: "", // 类型：属性类型
          key: Date.now(),
        },
      ];
      this.$forceUpdate();
      // this.$nextTick(() => {
      //   this.$refs["refAddForm"].clearValidate();
      // });
    },
    // 获取物模型
    async onThingModel(deviceType) {
      console.log(deviceType, "deviceType");
      let res = await reqByProductKey(deviceType);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { data } = res.data;
      this.options = [];
      this.options.push({
        name: "通配",
        items: [
          {
            type: "state",
            identifier: "state:*",
            name: "设备上下线",
          },
          {
            type: "event",
            identifier: "event:*",
            name: "任意事件上报",
          },
          {
            type: "service_reply",
            identifier: "service_reply:*",
            name: "任意服务回复",
          },
        ],
      });
      let items = [];
      this.options.push({
        name: "精确匹配",
        items: items,
      });
      if (!data) {
        return;
      }
      items.push({
        type: "property",
        identifier: "report",
        name: "属性上报",
      });
      data.model.events.forEach((item) => {
        items.push({
          type: "event",
          identifier: item.identifier,
          name: item.name,
        });
      });

      this.eventsList = data.model.events;
      this.eventsList.forEach((item) => {
        if (
          this.addForm.listeners[0].conditions[0].identifier == item.identifier
        ) {
          item.outputData.forEach((item2) => {
            console.log(item2.dataType, "item2.dataType");
            if (item2.dataType.type == "enum") {
              item2.dataType.specsArray = Object.keys(item2.dataType.specs).map(
                (key) => {
                  return {
                    key: parseInt(key),
                    value: item2.dataType.specs[key],
                  };
                }
              );
            } else if (item2.dataType.type == "bool") {
              item2.dataType.specsArray = Object.keys(item2.dataType.specs).map(
                (key) => {
                  return {
                    key: parseInt(key),
                    value: item2.dataType.specs[key],
                  };
                }
              );
            }
          });
          this.outputData = item.outputData;
        }
      });
      console.log(this.outputData, "this.outputData");
      // 服务
      // data.model.services.forEach(item => {
      //   items.push({
      //     type: 'service',
      //     identifier: item.identifier,
      //     name: item.name,
      //   })
      // })
      // data.model.services.forEach((s) => {
      //   this.servicesList.push(s);
      // });

      // 属性
      this.properties = [];
      // 任意
      // this.properties.push({
      //   identifier: '*',
      //   name: '任意',
      // })
      data.model.properties.forEach((item) => {
        let specsArray;
        if (item.dataType.type == "enum") {
          specsArray = Object.keys(item.dataType.specs).map((key) => {
            return { key: parseInt(key), value: item.dataType.specs[key] };
          });
        } else if (item.dataType.type == "bool") {
          specsArray = Object.keys(item.dataType.specs).map((key) => {
            return { key: parseInt(key), value: item.dataType.specs[key] };
          });
        }
        item.specsArray = specsArray;
        this.properties.push(item);
      });
    },
    // 选择条件
    async conditionChange(cond, index, e) {
      // 监听器:事件:属性要从事件的输出参数取
      this.listenerIndex = index;
      this.eventsList.forEach((item) => {
        if (item.identifier == e) {
          this.outputData = item.outputData;
        }
      });
      this.options.forEach((item) => {
        item.items.forEach((item2) => {
          if (item2.identifier == e) {
            // this.addForm.listeners[0].conditions[index].identifier = item2.identifier || "";
            this.addForm.listeners[0].conditions[index].type = item2.type || "";
            this.$set(
              this.addForm.listeners[0].conditions[index],
              "identifier",
              item2.identifier
            );
            return;
          }
        });
      });
      this.addForm.listeners[0].conditions[
        this.listenerIndex
      ].parameters[0].value = "";
      this.addForm.listeners[0].conditions[
        this.listenerIndex
      ].parameters[0].identifier = "";

      this.forceUpdate();
    },
    // 选择属性
    onChangeProperties(e, index) {
      console.log(e,"e")
      this.listenerIndex = index;
      this.properties.forEach((item) => {
        if (item.identifier == e) {
          this.propertySpecsArray = item.specsArray;
          this.addForm.listeners[0].conditions[
            this.listenerIndex
          ].parameters[0].value = "";
          this.addForm.listeners[0].conditions[
            this.listenerIndex
          ].parameters[0].comparator = "";
          this.addForm.listeners[0].conditions[this.listenerIndex].specsArray =
            item.specsArray;
          this.addForm.listeners[0].conditions[this.listenerIndex].specsType =
            item.dataType.type;
          this.addForm.listeners[0].conditions[this.listenerIndex].dataType =
            item.dataType;
        }
      });
      this.forceUpdate(true);
      this.$refs.refAddForm.validateField(
        `this.addForm.listeners[0].conditions[${this.listenerIndex}].identifier`
      );
    },
    // 选择事件
    onChangeEvents(e, index) {
      // 赋值事件具体信息
      this.eventsList.forEach((item) => {
        if (
          this.addForm.listeners[0].conditions[index].identifier ==
          item.identifier
        ) {
          item.outputData.forEach((item2) => {
            if (e == item2.identifier) {
              this.addForm.listeners[0].conditions[index].dataType =
                item2.dataType;
              this.addForm.listeners[0].conditions[index].specsType =
                item2.dataType.type;
              if (item2.dataType.type == "enum") {
                item2.dataType.specsArray = Object.keys(
                  item2.dataType.specs
                ).map((key) => {
                  return {
                    key: parseInt(key),
                    value: item2.dataType.specs[key],
                  };
                });
              } else if (item2.dataType.type == "bool") {
                item2.dataType.specsArray = Object.keys(
                  item2.dataType.specs
                ).map((key) => {
                  return {
                    key: parseInt(key),
                    value: item2.dataType.specs[key],
                  };
                });
              }
            }
          });
          // this.outputData = item.outputData;
        }
      });
      this.listenerIndex = index;
      this.addForm.listeners[0].conditions[
        this.listenerIndex
      ].parameters[0].value = "";
      this.addForm.listeners[0].conditions[
        this.listenerIndex
      ].parameters[0].comparator = "";

      this.forceUpdate(true);
    },

    // 强制更新
    forceUpdate(isPass = false) {
      if (isPass) {
        this.$forceUpdate();
      }
      if (JSON.stringify(this.editData) != "{}") {
        this.$forceUpdate();
      }
    },
    onAddCondition() {
      if (this.addForm.listeners[0].conditions.length >= 3) return;
      this.addForm.listeners[0].conditions.push({
        dataType: {},
        identifier: "", // 报告标识符：触发报告
        parameters: [
          // 参数：检查具体参数的值
          {
            identifier: "", // 标识符：门磁的ecl参数
            comparator: "", // 比较符：小于
            value: "", // 比较值：1
          },
        ],
        specsArray: [], // 规格数组
        specsType: "",
        type: "", // 类型：属性类型
        key: Date.now(),
      });
      this.forceUpdate(true);
    },
    // 移除条件
    onRemoveCondition(index) {
      this.addForm.listeners[0].conditions.splice(index, 1);
      this.forceUpdate();
    },

    // ———————— 执行源 ————————
    onSelectDeviceModel(currentIndex) {
      this.addForm.actions.forEach((item, index) => {
        if (index == currentIndex) {
          item.config.checked = true;
          this.currentExecuteIndex = currentIndex;
          if (item.config.services.length) {
            item.config.services.forEach((item2, index2) => {
              if (item2.inputData.length > 1) {
                item2.inputData.forEach((item3, index3) => {
                  if (item2.identifier == item3.identifier) {
                    this.currentDataItem = item3;
                  }
                });
              } else if (item2.inputData.length == 1) {
                this.currentDataItem = item2.inputData[0];
              }
            });
          }
          this.$nextTick(() => {
            this.watchIndex2++;
            if (
              this.addForm.actions[this.currentExecuteIndex].config.radius
                .type == "org"
            ) {
              this.rangeData2 =
                this.addForm.actions[
                  this.currentExecuteIndex
                ].config.radius.orgDn;
            } else if (
              this.addForm.actions[this.currentExecuteIndex].config.radius
                .type == "space"
            ) {
              this.rangeData2 =
                this.addForm.actions[
                  this.currentExecuteIndex
                ].config.radius.spaceDn;

              this.$refs.refRangeExecute.page = 1;
              this.$refs.refRangeExecute.getreqParkList();
            } else if (
              this.addForm.actions[this.currentExecuteIndex].config.radius
                .type == "device"
            ) {
              this.rangeData2 =
                this.addForm.actions[
                  this.currentExecuteIndex
                ].config.radius.deviceDn;
              this.$refs.refRangeExecute.pageDev = 1;
              this.$refs.refRangeExecute.getDataList();
            }
          });
        } else {
          item.config.checked = false;
        }
      });

      if (this.addForm.actions[currentIndex].config.pkIds.length) {
        // 用于判断当前选择的设备类型 防止切换后设置联动动作的第一个选择框options错乱
        this.currentDeviceType2 = this.addForm.actions[currentIndex].config.pk;
        // 后面有时间可以把serviceList挪进数组里做缓存
        // this.getCheckedNodes2("", currentIndex);
        this.onChangeCascader2([], false, currentIndex);
      }

      this.forceUpdate();
    },
    onChangeCascader2(e = [], clear = false, index = 0, init = false) {
      if (clear) {
        this.onClearExecuteConditions();
        let mark =
          this.$refs.refElcascader2[
            this.currentExecuteIndex
          ].getCheckedNodes()[0].data.label;
        this.addForm.actions[this.currentExecuteIndex].config.classMark = mark;
        this.addForm.executingDeviceType = `${this.currentDeviceType2},${mark}`;
        if (
          this.addForm.actions[this.currentExecuteIndex].config.radius.type ==
          "device"
        ) {
          this.changeRadio("device", "execute");
        }
      } else {
        if (!init) {
          let mark =
            this.$refs.refElcascader2[
              this.currentExecuteIndex
            ].getCheckedNodes()[0].data.label;
          this.addForm.actions[this.currentExecuteIndex].config.classMark =
            mark;
          this.addForm.executingDeviceType = `${this.currentDeviceType2},${mark}`;
          if (
            this.addForm.actions[this.currentExecuteIndex].config.radius.type ==
            "device"
          ) {
            this.changeRadio("device", "execute");
          }
        }
      }
      // 赋值
      if (this.productList.length) {
        let pkIds = this.addForm.actions[this.currentExecuteIndex].config.pkIds;
        let type = this.productList.filter((item) => item.id == pkIds[0])[0]
          .deviceType;
        this.currentDeviceType2 = type;
        this.addForm.actions[this.currentExecuteIndex].config.productId =
          pkIds[0];
      }
      this.currentExecuteIndex = index;
      this.addForm.actions[index].config.pk = this.currentDeviceType2;
      this.getProductObjectModel(this.currentDeviceType2);
    },
    // 清空触发条件
    onClearExecuteConditions() {
      this.addForm.actions[this.currentExecuteIndex].config.services = [
        {
          // 设备控制
          identifier: "",
          inputData: [
            {
              identifier: "",
              dataType: {
                type: "",
                specs: {},
                // typeList: [],
              },
              name: "",
              required: false,
              value: "",
            },
          ],
          saved: true,
          value: "", // 用于保存执行类型的值
        },
      ];
      this.$forceUpdate();
      // this.addForm.actions.forEach((item) => {
      //   item.config.services[0] = {
      //     // 设备控制
      //     identifier: "",
      //     inputData: [
      //       {
      //         identifier: "",
      //         dataType: {
      //           type: "",
      //           specs: {},
      //           // typeList: [],
      //         },
      //         name: "",
      //         required: false,
      //         value: "",
      //       },
      //     ],
      //     saved: true,
      //     value: "", // 用于保存执行类型的值
      //   };
      // });
    },
    // 获取物模型
    async getProductObjectModel(deviceType) {
      let res = await reqByProductKey(deviceType);
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      let { data } = res.data;
      this.initThingModel(data);
    },
    initThingModel(data) {
      this.propertiesList = [];
      this.servicesList = [];
      if (!data) return;
      // data.model.properties.forEach((p) => {
      //   this.propertiesList.push(p);
      // });
      data.model.services.forEach((s) => {
        this.servicesList.push(s);
      });
      // this.addForm.actions[index].config
      // this.onservices()

      // this.forceUpdate(true);
    },
    // 服务
    serviceSelected(e) {
      this.servicesList.forEach((s) => {
        if (e == s.identifier) {
          if (s.inputData.length) {
            s.inputData.forEach((item) => {
              if (item.dataType.type == "enum") {
                item.dataType.typeList = Object.entries(
                  item.dataType.specs
                ).map(([key, value]) => {
                  if (/^\d+$/.test(key)) {
                    // 如果是数字字符串，使用 parseInt 转换为数字
                    return { label: value, value: parseInt(key, 10) };
                  } else {
                    // 如果是普通字符串，直接使用字符串
                    return { label: value, value: key };
                  }
                });
              } else if (item.dataType.type == "bool") {
                item.dataType.typeList = Object.entries(
                  item.dataType.specs
                ).map(([key, value]) => {
                  // return { label: value, value: parseInt(key, 10) };
                  if (/^\d+$/.test(key)) {
                    // 如果是数字字符串，使用 parseInt 转换为数字
                    return { label: value, value: parseInt(key, 10) };
                  } else {
                    // 如果是普通字符串，直接使用字符串
                    return { label: value, value: key };
                  }
                });
              }
              // this.addForm.actions[
              //   this.currentExecuteIndex
              // ].config.services[0].equalValue = "";
              this.addForm.actions[
                this.currentExecuteIndex
              ].config.services[0].inputData = s.inputData;
              // this.addForm.actions[
              //   this.currentExecuteIndex
              // ].config.services[0].identifier = "";
              this.currentDataItem = {};
            });
          }
        }
      });
    },
    serviceSelectedItem(e, arr) {
      arr.forEach((s) => {
        if (e == s.identifier) {
          this.currentDataItem = s;
          if (s.dataType.type == "json") {
            this.addForm.actions[
              this.currentExecuteIndex
            ].config.services[0].value = s.dataType.specs;
          }
        }
      });
      this.forceUpdate(true);
    },
    // 转义
    processKeyValue(key, value) {
      // 判断 key 是否为数字字符串
      if (/^\d+$/.test(key)) {
        // 如果是数字字符串，使用 parseInt 转换为整数
        return { label: value, value: parseInt(key, 10) };
      } else {
        // 如果是字符串，直接使用原始值
        return { label: value, value: key };
      }
    },
    onChangeData(e) {
      this.$nextTick(() => {
        this.addForm.actions[
          this.currentExecuteIndex
        ].config.services[0].inputData[0].value = e;
      });
      this.forceUpdate();
    },

    // 添加设备型号
    onAddDeviceModel() {
      if (this.addForm.actions.length >= 5) return;
      this.addForm.actions.push({
        config: {
          id: Date.now(),
          services: [
            {
              // 设备控制
              identifier: "",
              inputData: [
                {
                  identifier: "",
                  dataType: {
                    type: "",
                    specs: {},
                  },
                  name: "",
                  required: false,
                  value: "",
                },
              ],
              saved: true,
              value: "",
              equalValue: "",
            },
          ],
          pk: "", // 设备主键：门磁
          type: "", //类型： all 全部 、org 组织、 space 单位、 device 设备
          radius: {
            type: "all", //类型： all 全部 、org 组织、 space 单位、 device 设备
            assemble: [], //集合id
            deviceDn: [],
            spaceDn: [],
            orgDn: [],
          },
          pkIds: "",
          checked: false,
          classMark: "",
        },
        type: "",
      });
    },
    // 移除设备型号
    onRemoveDeviceModel(index) {
      if (this.currentExecuteIndex != 0) {
        this.currentExecuteIndex = this.currentExecuteIndex - 1;
      }
      this.addForm.actions.splice(index, 1);
      this.$nextTick(() => {
        this.addForm.actions.forEach((item, i) => {
          if (i == this.currentExecuteIndex) {
            item.config.checked = true;
          } else {
            item.config.checked = false;
          }
        });
        this.onSelectDeviceModel(this.currentExecuteIndex);
        this.$forceUpdate();
      });
    },

    // 接收子组件的数据
    onPushData(data, type) {
      if (type == "trigger") {
        console.log(data, "data1");
        this.addForm.listeners[0].radius.assemble = data;
        if (this.addForm.listeners[0].radius.type == "org") {
          this.addForm.listeners[0].radius.orgAssemble = data;
        } else if (this.addForm.listeners[0].radius.type == "space") {
          this.addForm.listeners[0].radius.spaceAssemble = data;
        } else if (this.addForm.listeners[0].radius.type == "device") {
          this.addForm.listeners[0].radius.deviceAssemble = data;
        }
      } else {
        this.addForm.actions[this.currentExecuteIndex].config.radius.assemble =
          data;
        if (
          this.addForm.actions[this.currentExecuteIndex].config.radius.type ==
          "org"
        ) {
          this.addForm.actions[this.currentExecuteIndex].config.radius.orgDn =
            data;
        } else if (
          this.addForm.actions[this.currentExecuteIndex].config.radius.type ==
          "space"
        ) {
          this.addForm.actions[this.currentExecuteIndex].config.radius.spaceDn =
            data;
        } else if (
          this.addForm.actions[this.currentExecuteIndex].config.radius.type ==
          "device"
        ) {
          this.addForm.actions[
            this.currentExecuteIndex
          ].config.radius.deviceDn = data;
        }
      }
    },

    onBack() {
      this.$parent.isShowRuleOperate = false;
    },
    async addSubmit() {
      this.$refs.refAddForm.validate(async (valid) => {
        if (valid) {
          // copy一份addForm，方式提交失败时不能继续提交
          let addForm_copy = JSON.parse(JSON.stringify(this.addForm));

          // ____________处理分界线______________

          let triggerDeviceType = addForm_copy.listeners[0].classMark;
          let executingDeviceType = [];
          // 触发源
          let listeners = [];
          let listener_copy = JSON.parse(
            JSON.stringify(addForm_copy.listeners[0])
          );
          if (listener_copy.pkIds.length) {
            listener_copy.pkIds = listener_copy.pkIds.join(",");
          }

          // 将comparator没有值的默认给上"="
          listener_copy.conditions.forEach((i) => {
            if (!i.parameters[0].comparator) {
              i.parameters[0].comparator = "==";
            }
          });

          if (
            listener_copy.radius.type != "all" &&
            listener_copy.radius.assemble.some((element) => element == null)
          ) {
            return this.$modal.notifyWarning("触发源不能为空");
          }
          if (listener_copy.radius.type == "org") {
            if (
              !listener_copy.radius.assemble.length ||
              !listener_copy.radius.orgAssemble.length
            )
              return this.$modal.notifyWarning("触发源不能为空");
            listener_copy.radius.deviceAssemble = [];
            listener_copy.radius.spaceAssemble = [];
          } else if (listener_copy.radius.type == "space") {
            if (
              !listener_copy.radius.assemble.length ||
              !listener_copy.radius.spaceAssemble.length
            )
              return this.$modal.notifyWarning("触发源不能为空");
            let assembleIds = [];
            let spaceAssembleObjs = [];
            listener_copy.radius.deviceAssemble = [];
            // listener_copy.radius.spaceAssemble = [];
            listener_copy.radius.orgAssemble = [];
            // listener_copy.radius.assemble.forEach((i, index) => {
            listener_copy.radius.spaceAssemble.forEach((i, index) => {
              assembleIds.push(i.id);
              spaceAssembleObjs.push({ id: i.id, name: i.name });
              if (index == listener_copy.radius.assemble.length - 1) {
                listener_copy.radius.assemble = assembleIds;
                listener_copy.radius.spaceAssemble = spaceAssembleObjs;
              }
            });
          } else if (listener_copy.radius.type == "device") {
            if (
              !listener_copy.radius.assemble.length ||
              !listener_copy.radius.deviceAssemble.length
            )
              return this.$modal.notifyWarning("触发源不能为空");
            let assembleIds = [];
            let deviceAssembleObjs = [];
            // listener_copy.radius.deviceAssemble = [];
            listener_copy.radius.spaceAssemble = [];
            listener_copy.radius.orgAssemble = [];
            // listener_copy.radius.assemble.forEach((i, index) => {
            listener_copy.radius.deviceAssemble.forEach((i, index) => {
              assembleIds.push(i.imei);
              deviceAssembleObjs.push({ id: i.id, imei: i.imei });
              if (index == listener_copy.radius.assemble.length - 1) {
                listener_copy.radius.assemble = assembleIds;
                listener_copy.radius.deviceAssemble = deviceAssembleObjs;
              }
            });
          }
          delete listener_copy.config;
          listeners.push({
            config: JSON.stringify(listener_copy),
            type: "device",
          });

          // 执行源
          let actions = [];
          let actions_copy = JSON.parse(JSON.stringify(addForm_copy.actions));
          let flagActions = false;
          let errorIndex = 1;
          actions_copy.forEach((item, iindex) => {
            if (item.config.pkIds.length) {
              item.config.pkIds = item.config.pkIds.join(",");
            }
            item.config.checked = false;

            // 存储型号
            executingDeviceType.push(item.config.classMark);

            // if (
            //   item.config.radius.type != "all" &&
            //   item.config.radius.assemble.some((element) => element == null)
            // ) {
            //   flagActions = true;
            //   errorIndex = iindex + 1;
            // }
            // 处理传给后端的数组
            if (item.config.radius.type == "org") {
              if (
                !item.config.radius.assemble.length ||
                !item.config.radius.orgDn.length
              ) {
                flagActions = true;
                errorIndex = iindex + 1;
              }
              item.config.radius.deviceDn = [];
              item.config.radius.spaceDn = [];
            } else if (item.config.radius.type == "space") {
              if (
                !item.config.radius.assemble.length ||
                !item.config.radius.spaceDn.length
              ) {
                flagActions = true;
                errorIndex = iindex + 1;
              }
              let assembleIds = [];
              let spaceDnObjs = [];
              item.config.radius.deviceDn = [];
              // item.config.radius.spaceDn = [];
              item.config.radius.orgDn = [];
              // item.config.radius.assemble.forEach((i, index) => {
              item.config.radius.spaceDn.forEach((i, index) => {
                assembleIds.push(i.id);
                spaceDnObjs.push({ id: i.id, name: i.name });
                if (index == item.config.radius.assemble.length - 1) {
                  item.config.radius.assemble = assembleIds;
                  item.config.radius.spaceDn = spaceDnObjs;
                }
              });
            } else if (item.config.radius.type == "device") {
              if (
                !item.config.radius.assemble.length ||
                !item.config.radius.deviceDn.length
              ) {
                flagActions = true;
                errorIndex = iindex + 1;
              }
              let assembleIds = [];
              let deviceDnObjs = [];
              // item.config.radius.deviceDn = [];
              item.config.radius.spaceDn = [];
              item.config.radius.orgDn = [];
              // item.config.radius.assemble.forEach((i, index) => {
              item.config.radius.deviceDn.forEach((i, index) => {
                assembleIds.push(i.imei);
                deviceDnObjs.push({ id: i.id, imei: i.imei });
                if (index == item.config.radius.assemble.length - 1) {
                  item.config.radius.assemble = assembleIds;
                  item.config.radius.deviceDn = deviceDnObjs;
                }
              });
            }
            actions.push({
              config: JSON.stringify(item.config),
              type: "device",
            });
          });
          // 判断如果执行源为空则return
          if (flagActions)
            return this.$modal.notifyWarning(
              `第${errorIndex}个设备型号的执行源不能为空`
            );

          addForm_copy.listeners = listeners;
          addForm_copy.actions = actions;
          addForm_copy.tenantId = this.user.tenantId;
          addForm_copy.username = this.user.userName;

          if (JSON.stringify(this.editData) != "{}") {
            addForm_copy.id = this.editData.id;
          }

          addForm_copy.triggerDeviceType = triggerDeviceType;
          addForm_copy.executingDeviceType = executingDeviceType.join(",");
          let res = await reqRuleEdit(addForm_copy);
          if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

          if (JSON.stringify(this.editData) != "{}") {
            this.$modal.notifySuccess("编辑成功");
          } else {
            this.$modal.notifySuccess("新增成功");
          }

          this.$parent.getDataList();
          this.$parent.isShowRuleOperate = false;
        }
      });
    },
    closeAddDialog() {
      this.$parent.isShowRuleOperate = false;
    },
  },
};
</script>

<style scoped lang="less">
@import url("./ruleOperate.less");
</style>
